<template>
  <div class="mainContent">
    <div class="Content">
      <el-breadcrumb separator-class="el-icon-arrow-right" style="margin: 10px">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '' }">促销专区</el-breadcrumb-item>
      </el-breadcrumb>
      
      <!-- 搜索控件 -->
      <div style="padding-top: 10px">
        <el-form label-width="0px">
          <el-form-item label=" ">
            <el-input v-model="input" @keyup.enter="currentChange(1)" style="width: 350px"></el-input>
            <el-button v-preventReClicks type="primary" @click="currentChange(1)">查询</el-button>
            <router-link style="color: #409eff" :to="{ name: 'ShoppingCart', params: { Type: 'P' } }">
              <el-button v-preventReClicks type="primary" style="float: right">促销购物车</el-button>
            </router-link>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 促销类别 -->
      <div style="padding-top: 0px">
        <div class="prodlist" style="line-height: 30px;padding-left: 6px;font-size: 12px;position: relative;">
          <span class="prodlist_left">类别:</span>
          <div class="lb_right">
            <span class="prodlist_right" :class="ifShowCataId == '' ? 'active' : ''" @click="ifShowCataId = ''">
              全部</span>
            <span class="prodlist_right" 
                  :class="item.catalogNo == ifShowCataId ? 'active' : ''"
                  v-for="item in catalogList" 
                  :key="item.catalogNo" 
                  @click="ifShowCataId = item.catalogNo">
              {{ item.catalogName }}
            </span>
          </div>
          <span class="zzbtn" @click="toggleExpand(1)" v-if="catalogList.length > 16">
            <span v-if="zzbtn1"><i class="el-icon-arrow-down"></i>展开</span>
            <span v-else><i class="el-icon-arrow-up"></i>收起</span>
          </span>
        </div>
        
        <div class="prodlist" style="line-height: 30px;padding-left: 6px;font-size: 12px;position: relative;">
          <span class="prodlist_left">品牌:</span>
          <div class="lb_right">
            <span class="prodlist_right" :class="ifShowBrandId == '' ? 'active' : ''" @click="ifShowBrandId = ''">
              全部</span>
            <span class="prodlist_right" 
                  :class="item.brandNo == ifShowBrandId ? 'active' : ''" 
                  v-for="item in brandList"
                  :key="item.brandNo" 
                  @click="ifShowBrandId = item.brandNo">
              {{ item.brandName }}
            </span>
            <span class="zzbtn" @click="toggleExpand(2)" v-if="brandList.length > 16">
              <span v-if="zzbtn2"><i class="el-icon-arrow-down"></i>展开</span>
              <span v-else><i class="el-icon-arrow-up"></i>收起</span>
            </span>
          </div>
        </div>
      </div>
      
      <!-- 促销列表 -->
      <el-table v-loading="loading" 
                :data="stockLists" 
                stripe 
                border 
                style="width: 100%" 
                size="mini"
                :header-cell-style="{ textAlign: 'center', background: '#C1D4FE', color: '#606266' }"
                :cell-style="{ textAlign: 'center' }">
        <el-table-column label="商品编号" width="150">
          <template #default="scope">
            <router-link style="color:#409eff;" target="_blank"
              :to="{ path: '/promotionsDetail', query: { stkNo: scope.row.stkNo, validTime: scope.row.validTime } }">
              {{ scope.row.stkNo }}
            </router-link>
          </template>
        </el-table-column>
        <el-table-column prop="stkName" label="商品名称" width=" "></el-table-column>
        <el-table-column prop="casNo" label="CAS号" width="100"></el-table-column>
        <el-table-column prop="brandName" label="品牌/来源" width="80"></el-table-column>
        <el-table-column prop="spec" label="规格型号" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="unit" label="单位" width="50"></el-table-column>
        <el-table-column prop="validTime" label="有效期" width="85">
          <template #default="scope">
            <span>{{ showValidTime(scope.row.validTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标准价" prop="price" width="70"></el-table-column>
        <el-table-column label="促销价" prop="promotionPrice" width="70">
          <template #default="scope">
            <span :style="showVipPrice(scope.row.promotionPrice, scope.row.priceBZ) && 'color :red'">
              {{ showVipPrice(scope.row.promotionPrice, scope.row.priceBZ) ? scope.row.promotionPrice : '暂无' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="库存与期货" prop="qtyMemo" width="90"></el-table-column>
        <el-table-column label="数量" class="num" width="110">
          <template #default="scope">
            <el-input-number :precision="0" 
                            size="mini" 
                            style="width: 80px; display: inline-block"
                            controls-position="right" 
                            :min="scope.row.minQty" 
                            v-model="scope.row.tryQty"
                            :max="scope.row.qty"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="出库仓" prop="warehouse" width="65"></el-table-column>
        <el-table-column label="购 买" width="60">
          <template #default="scope">
            <i @click="addToCart(scope.row)" 
               class="el-icon-shopping-cart-full"
               style="font-size: 30px; color: #409eff"></i>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination background 
                       layout="total,prev, pager, next ,jumper" 
                       :page-size="pageSize" 
                       :total="total"
                       :current-page="currentPage" 
                       @current-change="currentChange"></el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { GetPromotionStockListPage } from "@/api/Products"
import { AddShoppingCartStock } from "@/api/ShoppingCart"
import { dateFormat } from "@/libs/RegExp.js"

const store = useStore()
const router = useRouter()

// 响应式数据
const input = ref('')
const ifShowCataId = ref('')
const ifShowBrandId = ref('')
const pageSize = ref(28)
const currentPage = ref(1)
const total = ref(0)
const catalogList = ref([])
const brandList = ref([])
const stockLists = ref([])
const zzbtn1 = ref(true)
const zzbtn2 = ref(true)
const loading = ref(false)
const cusId = ref(localStorage.getItem('cusId'))
const webId = ref(localStorage.getItem('webId'))

// 计算属性
const showValidTime = computed(() => {
  return (date) => dateFormat(date, "yyyy-mm-dd")
})

const showVipPrice = computed(() => {
  return (price, priceBZ) => price != 0 && (price != priceBZ)
})

// 方法
const toggleExpand = (num) => {
  const target = document.querySelector(`.lb_right:nth-of-type(${num})`)
  if (zzbtn1.value) {
    target.style.maxHeight = "none"
  } else {
    target.style.maxHeight = "60px"
  }
  if (num === 1) zzbtn1.value = !zzbtn1.value
  if (num === 2) zzbtn2.value = !zzbtn2.value
}

const currentChange = (page) => {
  currentPage.value = page
  fetchPromotionStockList()
}

const addToCart = (data) => {
  if (!cusId.value) {
    store.commit('setShowLogin', true)
    return false
  }
  
  const params = {
    cusId: cusId.value,
    webId: webId.value,
    type: "P",
    jfType: "",
    details: [{
      stkNo: data.stkNo,
      qty: data.tryQty || 1,
      price: data.promotionPrice,
      validTime: dateFormat(data.validTime, "yyyy-mm-dd HH:MM:ss") ? 
               (dateFormat(data.validTime, "yyyy-mm-dd HH:MM:ss") + ".000") : "",
    }]
  }

  AddShoppingCartStock(params).then(res => {
    if (res.code == 2000) {
      ElMessage.success("商品已加入购物车!")
      // 触发购物车数量更新事件
      // 在Vue3中，可以使用mitt或其他事件总线方案
      // 或者直接调用store action更新购物车数量
    } else {
      ElMessage.error("商品加入购物车失败!")
    }
  })
}

const fetchPromotionStockList = async () => {
  loading.value = true
  try {
    const res = await GetPromotionStockListPage({
      BrandNo: ifShowBrandId.value,
      CatalogNo: ifShowCataId.value,
      Search: input.value,
      SkipCount: (currentPage.value - 1) * pageSize.value,
      MaxResultCount: pageSize.value, 
      nocache: 1
    })
    
    if (res.code === 2000) {
      total.value = res.data.count
      catalogList.value = res.data.catalogList
      brandList.value = res.data.brandList
      stockLists.value = res.data.promotionStockLists
    }
  } finally {
    loading.value = false
  }
}

// 监听器
watch(ifShowCataId, () => {
  currentChange(1)
})

watch(ifShowBrandId, () => {
  currentChange(1)
})

// 生命周期钩子
onMounted(() => {
  fetchPromotionStockList()
})
</script>

<style lang="scss" scoped>
.Content {
  width: 1226px;
  margin: 0 auto;
  font-size: 16px;
}

.el-input-number {
  display: inline;
}

a:hover {
  color: #409eff;
}

.pagination {
  text-align: center;
  padding: 18px 0 20px 0;
}

.el-input__inner {
  padding-left: 7px;
  padding-right: 35px;
}

.prodlist_left {
  padding-left: 5px;
  height: 40px;
  width: 86px !important;
  display: inline-block;
  float: left;
}

.prodlist_right {
  color: #333;
  border-left: 1px solid #e0cabf;
  padding: 0 10px;
  cursor: pointer;
  
  &:hover {
    color: #0088ff;
  }
}

.prodlist {
  list-style: 40px;
  padding-left: 6px;
  clear: both;
}

.lb_right {
  width: 1050px;
  float: left;
  max-height: 60px;
  overflow: hidden;
}

.el-table-column .cell {
  font-size: 12px;
}

.el-form-item {
  margin-bottom: 12px;
}

.active {
  color: #409eff;
}

.zzbtn {
  position: absolute;
  right: 7px;
  color: #409eff;
  cursor: pointer;
}
</style>